
from datetime import date

from django.core.paginator import Paginator, PageNotAnInteger
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import ListView, DetailView

from post.models import Topic


# Create your views here.

def hello(request):
    return HttpResponse('hello 视图')


def showData(request, urlData):
    d = date.today()
    s = str(d) + "<br>" + urlData
    return HttpResponse(s)

def useRedirect(request):
    # 重定向到之前已定义的视图函数showData
    return redirect('logon')

# @csrf_exempt  # 免除CSRF保护
# def login(request):
#     if request.method == 'GET':
#         ip_addr = request.META['REMOTE_ADDR']
#         return render(request, 'login.html', {'ip': ip_addr})
#     elif request.method == 'POST':
#         username = request.POST['username']
#         password = request.POST.get('pwd', '')
#         if username == 'admin' and password == '123456':
#             return redirect('welcome')
#         else:
#             return redirect('login')

@method_decorator(csrf_exempt, name='dispatch')
class LoginView(View):
    def get(self, request):
        ip_addr = request.META['REMOTE_ADDR']
        return render(request, 'login.html', {'ip': ip_addr})
    def post(self, request):
        username = request.POST['username']
        password = request.POST.get('pwd', '')
        if username == 'admin' and password == '123456':
            return redirect('welcome')
        else:
            return redirect('login')

# 欢迎页面函数
def welcome(request):
    return render(request, 'welcome.html')

# 动态路由视图函数(URL参数传递)
def dynamic_hello(request, year, month, day=1): # TODO
    return HttpResponse(
        f'{year}-{month}-{day} Hello Django BBS' # TODO
    )

def hello_template(req):
    return render(req, 'hello_template.html',
                  {'data': '大数据'})

# 14-模板基础-话题列表
# def topic_list(req):
#     topic_data = Topic.objects.all()
#
#     return render(req,
#                     'topic_list.html',
#                             {'topics': topic_data})

class TopicListView(ListView):
    model = Topic

# 14-模板基础-话题列表分页
def topic_list_page(req, page=1):
    topic_data = Topic.objects.all()

    paginator = Paginator(topic_data, 5)

    try:
        topic_data_page = paginator.page(page)
    except PageNotAnInteger:
        topic_data_page = paginator.page(1)

    return render(req, 'topic_list_page.html',
                    {'topic_count':topic_data.count(),
                        'topics': topic_data_page})


# 14-模板基础-话题详情
class TopicDetailView(DetailView):
    model = Topic
    # template_name = 'topic_detail.html'
    # context_object_name = 'topic'
    # pk_url_kwarg = 'id'  # 对应 URL 中的 id 参数



